package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager.WakeLock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.enums.MediaState;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.CarlaClassicVo;
import com.jdy.haoduoai.model.LeHotRecomStory;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageLoader;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.RoundImageView;
import com.jdy.haoduoai.widget.progressbar.DonutProgress;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.Subscription;

//import com.jdy.haoduoai.R;

/**
 * 讲故事完成
 * 
 * @author hf
 * 
 */
@SuppressLint({ "SimpleDateFormat", "HandlerLeak", "InflateParams" })
public class FinishTellStoryActivity extends BaseActivity implements
    OnClickListener, Callback {

  @InjectView(id = R.id.toplays, click = true)
  private RelativeLayout shareplaylayout;
  @InjectView(id = R.id.back, click = true)
  private View back;
  @InjectView(id = R.id.shareimgs)
  private ImageView shareimg;
  @InjectView(id = R.id.sv_video)
  private SurfaceView sv_video;
  @InjectView(id = R.id.playbtn, click = true)
  private Button playbtn;
  @InjectView(id = R.id.download_progress)
  private DonutProgress donutProgress;
  @InjectView(id = R.id.endtime)
  private TextView endtime;
  @InjectView(id = R.id.usetime)
  private TextView usetime; // 已经播放时间
  @InjectView(id = R.id.seek)
  private SeekBar seekBar;
  @InjectView(id = R.id.headicon)
  private RoundImageView headicon;
  @InjectView(id = R.id.editor)
  private TextView editor;
  @InjectView(id = R.id.custom_channel)
  private LinearLayout custom_channel;
  @InjectView(id = R.id.btn_push, click = true)
  private Button btn_push;

  private SurfaceHolder surfaceHolder;
  private MediaPlayer mp4Player;
  private MediaState mMediaState = MediaState.Downloaded;
  @SuppressWarnings("unused")
  private String userComments;

  private int idStory, uid, playtime;

  private LeUser mLeUser;
  private String coverUrl;
  private int banner_id = -1;

  boolean isPause; // 是否已经暂停了
  private Subscription mSubscription;
  // 记录暂停播放的位置
  private int currentPosition = 0;
  private String filePath; // mp4 文件路径
  private WakeLock mWakeLock;

  private int currentMP4Position;

  private ImageLoader mImageLoader;
  private ArrayList<LeHotRecomStory> mRecommendStroyList = null;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_finish_tellstory);
    hideTitleView();
    initialize();
    initListener();
    initHandler();
    setVideoHeight();

    // 为你推荐
    loadRecommendStory();
  }

  private void setVideoHeight() {
    DisplayMetrics metrics = getResources().getDisplayMetrics();

    int w = metrics.widthPixels;

    int h = w * 3 / 4;

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, h);

    shareplaylayout.setLayoutParams(params);

    RelativeLayout.LayoutParams seekBarParams = (RelativeLayout.LayoutParams) seekBar
        .getLayoutParams();

    seekBarParams.topMargin = h - Tools.getPixelByDip(this, 10);

    seekBar.setLayoutParams(seekBarParams);
    seekBar.setEnabled(false);
  }

  private CarlaClassicVo convert2CarlaClassicVo(LeHotRecomStory recommendStroy) {
    if (recommendStroy == null)
      return null;
    LeHotRecomStory lhr = recommendStroy;
    CarlaClassicVo ccv = new CarlaClassicVo();

    ccv.id = lhr.id; // );
    ccv.category_id = lhr.category_id; // );
    ccv.catalog = lhr.catalog; // );
    ccv.name = lhr.name; // );
    ccv.cover = lhr.cover;// );
    ccv.url = lhr.url;// );
    ccv.enabled = lhr.enabled; // );
    ccv.sort = lhr.sort; // );
    ccv.length = lhr.length; // );
    ccv.agefrom = 0; // );
    ccv.ageto = 0;
    ccv.lines = lhr.lines; // );
    ccv.created_at = lhr.created_at; // );
    ccv.updated_at = lhr.updated_at; // );
    ccv.deleted_at = lhr.deleted_at; // );
    ccv.followers = lhr.followers;// );
    ccv.corner_icon = lhr.corner_icon; // );
    ccv.author = lhr.author; // );
    ccv.tags = lhr.tags; // );

    // ccv.setId(lhr.id);
    // ccv.setCategory_id(lhr.category_id);
    // ccv.setCatalog(lhr.catalog);
    // ccv.setName(lhr.name);
    // ccv.setCover(lhr.cover);
    // ccv.setUrl(lhr.url);
    // ccv.setEnabled(lhr.enabled);
    // ccv.setSort(lhr.sort);
    // ccv.setLength(lhr.length);
    // ccv.setAgefrom(0);
    // ccv.setAgeto(0);
    // ccv.setLines(lhr.lines);
    // ccv.setCreated_at(lhr.created_at);
    // ccv.setUpdated_at(lhr.updated_at);
    // ccv.setDeleted_at(lhr.deleted_at);
    // ccv.setFollowers(lhr.followers);
    // ccv.setCorner_icon(lhr.corner_icon);
    // ccv.setAuthor(lhr.author);
    // ccv.setTags(lhr.tags);
    return ccv;
  }

  private void setRecommendStoryView(List<LeHotRecomStory> rList) {
    custom_channel.removeAllViews();
    int i = 0;
    int size = rList.size();
    for (; i < size; i++) {
      final LeHotRecomStory lhr = rList.get(i);
      View hChild = LayoutInflater.from(this).inflate(
          R.layout.horizontallist_item, null);
      final ImageView coverImg = (ImageView) hChild.findViewById(R.id.img);
      ImageView playStateImg = (ImageView) hChild
          .findViewById(R.id.play_state_img);
      playStateImg.setVisibility(View.GONE);
      coverImg.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
          // TODO Auto-generated method stub
          Intent recode = new Intent();

          Bundle bundle = new Bundle();

          bundle.putSerializable("carlaclassic", convert2CarlaClassicVo(lhr));

          recode.putExtras(bundle);

          recode.setClass(FinishTellStoryActivity.this, RecordActivity2.class);

          startActivity(recode);
        }
      });
      coverImg.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

      TextView titleTv = (TextView) hChild.findViewById(R.id.tittle);

      titleTv.setText(lhr.name);

      if (Tools.isNotEmpty(lhr.cover))
        Picasso.with(this).load(lhr.cover)
            .placeholder(getResources().getDrawable(R.drawable.default_cover))
            .error(getResources().getDrawable(R.drawable.default_cover))
            .into(coverImg, new com.squareup.picasso.Callback() {

              @Override
              public void onSuccess() {
                // TODO Auto-generated method stub

              }

              @Override
              public void onError() {
                if (mImageLoader == null) {
                  mImageLoader = new ImageLoader(FinishTellStoryActivity.this);
                }
                mImageLoader.DisplayImage(lhr.cover, coverImg, false);
              }
            });

      LinearLayout.LayoutParams params_image = new LinearLayout.LayoutParams(
          LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

      params_image.setMargins(Tools.getPixelByDip(this, 5), 0,
          Tools.getPixelByDip(this, 5), 0);

      hChild.setLayoutParams(params_image);

      custom_channel.addView(hChild);
    }
  }

  private void loadRecommendStory() {

    if (mLeUser == null) {
      mLeUser = Tools.restoreLeUser();
    }

    new CustomAsyncTask(this, new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          if (mRecommendStroyList != null) {
            mRecommendStroyList.clear();
          }

          if (Tools.isNotEmpty(result.data)) {
            mRecommendStroyList = (ArrayList<LeHotRecomStory>) JsonSerializer
                .getInstance().deserialize(result.data, ArrayList.class,
                    LeHotRecomStory.class);
            setRecommendStoryView(mRecommendStroyList);
          }
        }

      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        return HttpUtils.startRequest(HttpUtils.HOST_API
            + "/api/2.0/catalog/story/recommand", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  @Override
  public void onPause() {
    super.onPause();
    if (mWakeLock != null) {
      mWakeLock.release();
    }

    if (mp4Player != null && mp4Player.isPlaying()) {
      mp4Player.pause();
      currentMP4Position = mp4Player.getCurrentPosition();
      isPause = true;
    }

  }

  @Override
  public void onResume() {
    super.onResume();
    if (mWakeLock != null) {
      mWakeLock.acquire();
    }
  }

  private void initListener() {
    // seekBar.setOnSeekBarChangeListener(new SeekBarChangeEvent());
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (mSubscription != null) {
      mSubscription.unsubscribe();
    }
    if (handler != null) {
      handler.removeCallbacksAndMessages(null);
      handler = null;
    }
  }

  private void initHandler() {
    handler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (!Thread.currentThread().isInterrupted()) {
          switch (msg.what) {
          case 5:
            usetime.setText(DateUtils.getTime(playtime / 1000));
            seekBar.setProgress(playtime / 1000);
            break;
          default:
            break;
          }
        }

      }
    };
  }

  private void initialize() {
    mLeUser = ((LeXiaoXiaoBanApp) this.getApplication()).getUser();

    String pathBase = Environment.getExternalStorageDirectory()
        .getAbsolutePath() + "/" + getPackageName();

    filePath = pathBase + "/finalvideo.mp4";

    if (getIntent() != null) {
      coverUrl = getIntent().getStringExtra("pic2");
      idStory = getIntent().getIntExtra("id", -1);

      banner_id = getIntent().getIntExtra("banner_id", -1);
    }

    mImageLoader = new ImageLoader(this);
    mImageLoader.DisplayImage(coverUrl, shareimg, false);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_push:
      playvideo(idStory);
      break;
    case R.id.back:
      finish();
      break;
    case R.id.toplays:
      if (sv_video.isShown()) {
        if (mMediaState.equals(MediaState.Playing)) {// precondition must be
          mMediaState = MediaState.Pause;
          playbtn.setVisibility(View.VISIBLE);

          if (mp4Player != null && mp4Player.isPlaying()) {
            mp4Player.pause();
            currentMP4Position = mp4Player.getCurrentPosition();
            isPause = true;
          }
        } else if (mMediaState.equals(MediaState.Pause)) {
          mMediaState = MediaState.Playing;
          playbtn.setVisibility(View.GONE);

          if (mp4Player != null) {
            mp4Player.start();
          }
        }
      } else {
      }
      break;
    case R.id.playbtn:
      File file = new File(filePath);
      if (file.exists()) {
        if (mMediaState == MediaState.Pause) {
          mMediaState = MediaState.Playing;
          playbtn.setVisibility(View.GONE);

          if (mp4Player != null) {
            mp4Player.start();
            new Thread(new UIUpdateThread()).start();
          }
        } else {
          play();
        }
      }
      break;
    case R.id.tellone: // tell a story
      Intent intent = new Intent();
      intent.setClass(this, PrivateStoryActivity.class);
      intent.putExtra("titles", "经典卡拉OK");
      startActivity(intent);
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      break;
    case R.id.pushto: // push to device
      playvideo(idStory);
      break;

    default:
      break;
    }

  }

  // public String getName(String url) {
  // String[] out = null;
  // try {
  // out = URLDecoder.decode(url, "UTF-8").split("/");
  // } catch (UnsupportedEncodingException e) {
  // e.printStackTrace();
  // }
  // String path = Environment.getExternalStorageDirectory()
  // + "/haoduoai/share/" + out[out.length - 1];
  // return path;
  // }

  private void playvideo(final int sid) {
    new CustomAsyncTask(FinishTellStoryActivity.this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          toastShow("已推送到设备播放");
//          if (LeConfig.isDeviceConnect) {
//            toastShow("已推送到设备播放");
//          } else {
//            toastShow("未连接到设备，请检查设备联网情况！");
//          }
        } else {
          LeConfig.isDeviceConnect = false;
          toastShow("设备不在线");
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        int volume = -1, minutes = -1;

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        param_.put(HttpUtils.TAG_OPERATION_I, "book");
       // param_.put("mode", "im");
        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }
        if (uid != -1) {
          param_.put(HttpUtils.TAG_UID_I, String.valueOf(uid));
        }
        if (volume != -1) {
          param_.put(HttpUtils.TAG_VOLUME, String.valueOf(volume));
        }
        if (minutes != -1) {
          param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));
        }
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        if (banner_id >= 0) {
          param_.put("reference", "banner");
          param_.put("banner_id", banner_id);
        } else {
          param_.put("reference", "push");
        }

        param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  /**
   * 播放
   */
  @SuppressWarnings("deprecation")
  private void play() {
    if (isPause) {
      if (mp4Player != null) {
        mp4Player.seekTo(currentPosition);
        mp4Player.start();
      }
      isPause = false;
    } else {
      if (mp4Player != null) {
        if (mp4Player.isPlaying()) {
          System.out.println("视频处于播放状态");
        }
      } else {
        playbtn.setVisibility(View.GONE);
        sv_video.setVisibility(View.VISIBLE);
        surfaceHolder = sv_video.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
      }
    }
  }

  // public void resetVideo() {
  // if (mp4Player != null && mp4Player.isPlaying()) {
  // mp4Player.seekTo(0);
  // mp4Player.start();
  // }
  // }

  // public void pasueVideo() {
  // if (mp4Player != null && mp4Player.isPlaying()) {
  // mp4Player.pause();
  // currentPosition = mp4Player.getCurrentPosition();
  // isPause = true;
  // }
  // }

  // public void stopVideo() {
  // if (mp4Player != null && mp4Player.isPlaying()) {
  // mp4Player.stop();
  // mp4Player.release();
  // mp4Player = null;
  // isPause = false;
  // }
  // }

  /**
   * 调用此方法输入所要转换的时间戳输入例如（1402733340）输出（"2014年06月14日16时09分"）
   * 
   * @param time
   * @return
   */
  // public String timet(String time) {
  // SimpleDateFormat sdr = new SimpleDateFormat("HH:mm");
  // int i = Integer.parseInt(time);
  // String times = sdr.format(new Date(i * 1000L));
  // return times;
  // }

  @Override
  public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
    Log.i("通知", "surfaceHolder被改变了");
  }

  @Override
  public void surfaceCreated(SurfaceHolder arg0) {
    Log.i("通知", "surfaceHolder被create了");

    new AsyncTask<Void, Void, Void>() {

      @Override
      protected void onPreExecute() {
        playbtn.setVisibility(View.GONE);
      }

      @Override
      protected Void doInBackground(Void... params) {
        mp4Player = new MediaPlayer();
        mp4Player.setDisplay(surfaceHolder);
        mp4Player.setOnCompletionListener(new OnCompletionListener() {
          @Override
          public void onCompletion(MediaPlayer arg0) {
            if (mp4Player != null) {
              mp4Player.release();
              mp4Player = null;
            }
          }
        });
        mp4Player.setOnErrorListener(new OnErrorListener() {
          @Override
          public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
            if (mp4Player != null) {
              mp4Player.release();
              mp4Player = null;
            }
            return false;
          }
        });
        try {
          mp4Player.setDataSource(filePath);
          mp4Player.prepare();
          mp4Player.seekTo(currentMP4Position);
          mp4Player.start();

          isPause = false;

          mMediaState = MediaState.Playing;
        } catch (Exception e) {
          e.printStackTrace();
        }
        return null;
      }

      @Override
      protected void onPostExecute(Void result) {
        seekBar.setMax(mp4Player.getDuration() / 1000);
        endtime.setText(" / "
            + DateUtils.getTime(mp4Player.getDuration() / 1000));
        new Thread(new UIUpdateThread()).start();
      }

    }.execute((Void[]) null);

  }

  @Override
  public void surfaceDestroyed(SurfaceHolder arg0) {
    Log.i("通知", "surfaceHolder被销毁了");

    if (mp4Player != null && mp4Player.isPlaying()) {
      mp4Player.stop();
    }

    // if (mp3Player != null && mp3Player.isPlaying()) {
    // mp3Player.stop();
    // }
  }

  class UIUpdateThread implements Runnable {
    long time = 500; // 滚动速度

    @Override
    public void run() {
      while (mp4Player != null && mp4Player.isPlaying()) {
        playtime = mp4Player.getCurrentPosition();
        handler.sendEmptyMessage(5);
        try {
          Thread.sleep(time);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  // class SeekBarChangeEvent implements OnSeekBarChangeListener {
  // @Override
  // public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
  // }
  //
  // @Override
  // public void onStartTrackingTouch(SeekBar arg0) {
  // // 开始拖动进度条
  // // isChanging = true;
  // }
  //
  // @Override
  // public void onStopTrackingTouch(SeekBar arg0) {
  // // 停止拖动进度条
  // // mp3Player.seekTo(arg0.getProgress());
  // // mp4Player.seekTo(arg0.getProgress());
  // // 将media进度设置为当前seekbar的进度
  // // isChanging = false;
  // // if (mp3Player != null && mp3Player.isPlaying()) {
  // // mp3Player.seekTo(arg0.getProgress() * 1000);
  // // mp3Player.start();
  // // }
  // if (mp4Player != null && mp4Player.isPlaying()) {
  // mp4Player.seekTo(arg0.getProgress() * 1000);
  // mp4Player.start();
  // }
  // }
  // }

  // private void setRecomChannelView() {
  // custom_channel.removeAllViews();
  //
  // View line = new View(this);
  // line.setBackgroundColor(getResources().getColor(R.color.hint));
  // custom_channel.addView(line, new LinearLayout.LayoutParams(-2, 1));
  //
  // int pCount = 0;
  //
  // if (pCount > 15) {
  // pCount = 15;
  // }
  //
  // if (pCount <= 0) {
  // return;
  // }
  //
  // Context ctx = LeXiaoXiaoBanApp.getInstance().getAppContext();
  //
  // // 可横向滑动，展示数量为15个
  // for (int i = 0; i < pCount; i++) {
  // View v = LayoutInflater.from(this).inflate(R.layout.channel_list_item,
  // custom_channel, false);
  //
  // custom_channel.addView(v);
  // final ImageView channelIcon = (ImageView) v
  // .findViewById(R.id.iv_channelicon);
  // channelIcon.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
  // ImageView favIcon = (ImageView) v.findViewById(R.id.FavorAppIcon);
  // final TextView title = (TextView) v.findViewById(R.id.tv_title);
  // // title.setText(item.name);
  // v.setOnClickListener(new OnClickListener() {
  // @Override
  // public void onClick(View v) {
  // // if (LeConfig.isPushDialogUP) {
  // // // showsuccessdialog(item);
  // // } else {
  // // showToast("内容已经发送到小小班");
  // // }
  // }
  // });
  //
  // // if (mImageLoader == null) {
  // // mImageLoader = new ImageLoader(getActivity());
  // // }
  //
  // // if (Tools.isNotEmpty(item)) {
  // // if (item.status == 1) {
  // // favIcon.setImageResource(R.drawable.finish_recom_icon);
  // // } else {
  // // // TODO
  // // }
  //
  // // Picasso.with(this).load(item.album_cover)
  // // .into(channelIcon, new com.squareup.picasso.Callback() {
  // // @Override
  // // public void onSuccess() {
  // // }
  // //
  // // @Override
  // // public void onError() {
  // // if (mImageLoader == null) {
  // // mImageLoader = new ImageLoader(getActivity());
  // // }
  // // mImageLoader.DisplayImage(item.album_cover, channelIcon, false);
  // // }
  // // });
  // // }
  //
  // LinearLayout.LayoutParams params_image = new LinearLayout.LayoutParams(
  // LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
  // params_image.setMargins(Tools.getPixelByDip(this, 5), 0,
  // Tools.getPixelByDip(this, 5), 0);
  // params_image.setMargins(Tools.getPixelByDip(ctx, 5), 0,
  // Tools.getPixelByDip(ctx, 5), 0);
  // v.setLayoutParams(params_image);
  // }
  //
  // line = new View(this);
  // line.setBackgroundColor(this.getResources().getColor(R.color.hint));
  // custom_channel.addView(line, new LinearLayout.LayoutParams(-2, 1));
  // }

}
